package com.christina.engine.response.decorator.impl;

import com.christina.engine.response.decorator.ResponseDecorator;
import com.christina.engine.response.decorator.ResponseGenerator;
import com.christina.engine.response.model.ResponseContext;
import com.christina.engine.response.model.ResponseResult;
import org.springframework.stereotype.Component;

/**
 * 日志响应装饰器
 * 为响应生成过程添加详细的日志记录
 * 
 * @author Christina
 */
@Component
public class LoggingResponseDecorator extends ResponseDecorator {
    
    private static final String DECORATOR_NAME = "LoggingDecorator";
    private static final int PRIORITY = 100; // 高优先级，最先执行
    
    public LoggingResponseDecorator(ResponseGenerator wrapped) {
        super(wrapped, DECORATOR_NAME, PRIORITY);
    }
    
    // 无参构造函数，用于Spring注入
    public LoggingResponseDecorator() {
        super(null, DECORATOR_NAME, PRIORITY);
    }
    
    @Override
    protected void preDecorate(ResponseContext context) {
        logger.info("开始生成响应 - RequestId: {}, UserId: {}, Intent: {}", 
                context.getRequestId(), 
                context.getUserId(),
                context.getRecognizedIntent() != null ? 
                        context.getRecognizedIntent().getType() : "UNKNOWN");
        
        logger.debug("响应上下文详情 - UserInput: {}, ResponseType: {}", 
                context.getUserInput(), 
                context.getResponseType());
    }
    
    @Override
    protected ResponseResult decorate(ResponseContext context, ResponseResult result) {
        return doDecorate(result, context);
    }
    
    @Override
    protected ResponseResult doDecorate(ResponseResult result, ResponseContext context) {
        // 记录响应生成结果
        if (result.isSuccess()) {
            logger.info("响应生成成功 - RequestId: {}, ContentLength: {}, Quality: {:.2f}", 
                    context.getRequestId(),
                    result.getContent() != null ? result.getContent().length() : 0,
                    result.getQualityScore());
            
            logger.debug("响应内容预览 - RequestId: {}, Content: {}", 
                    context.getRequestId(),
                    truncateContent(result.getContent(), 100));
        } else {
            logger.warn("响应生成失败 - RequestId: {}, Error: {}", 
                    context.getRequestId(),
                    result.getErrorMessage());
        }
        
        // 记录性能信息
        if (result.getGenerationDurationMs() > 0) {
            logger.debug("响应生成耗时 - RequestId: {}, Duration: {}ms", 
                    context.getRequestId(),
                    result.getGenerationDurationMs());
        }
        
        // 添加日志相关的元数据
        result.addMetadata("logged", true);
        result.addMetadata("log_level", getLogLevel(result));
        result.addMetadata("log_timestamp", System.currentTimeMillis());
        
        return result;
    }
    
    @Override
    protected void postDecorate(ResponseContext context, ResponseResult result) {
        // 记录装饰完成信息
        logger.debug("日志装饰完成 - RequestId: {}, Generator: {}", 
                context.getRequestId(),
                result.getGeneratorName());
        
        // 如果质量分数较低，记录警告
        if (result.getQualityScore() < 0.6) {
            logger.warn("响应质量较低 - RequestId: {}, Quality: {:.2f}, 建议检查生成逻辑", 
                    context.getRequestId(),
                    result.getQualityScore());
        }
        
        // 记录元数据统计
        if (result.getMetadata() != null && !result.getMetadata().isEmpty()) {
            logger.debug("响应元数据 - RequestId: {}, MetadataCount: {}", 
                    context.getRequestId(),
                    result.getMetadata().size());
        }
    }
    
    @Override
    protected boolean shouldDecorate(ResponseContext context) {
        // 总是进行日志装饰，但可以根据配置或上下文条件进行控制
        return true;
    }
    
    @Override
    protected ResponseResult handleDecorationError(ResponseContext context, Exception exception) {
        logger.error("日志装饰器异常 - RequestId: {}, Error: {}", 
                context.getRequestId(), 
                exception.getMessage(), 
                exception);
        
        // 即使日志装饰失败，也要尝试返回原始结果
        return super.handleDecorationError(context, exception);
    }
    
    /**
     * 截断内容用于日志显示
     * 
     * @param content 原始内容
     * @param maxLength 最大长度
     * @return 截断后的内容
     */
    private String truncateContent(String content, int maxLength) {
        if (content == null) {
            return "null";
        }
        
        if (content.length() <= maxLength) {
            return content;
        }
        
        return content.substring(0, maxLength) + "...";
    }
    
    /**
     * 根据响应结果确定日志级别
     * 
     * @param result 响应结果
     * @return 日志级别
     */
    private String getLogLevel(ResponseResult result) {
        if (!result.isSuccess()) {
            return "ERROR";
        } else if (result.getQualityScore() < 0.6) {
            return "WARN";
        } else {
            return "INFO";
        }
    }
    
    /**
     * 创建包装指定生成器的日志装饰器
     * 
     * @param generator 要包装的生成器
     * @return 日志装饰器实例
     */
    public static LoggingResponseDecorator wrap(ResponseGenerator generator) {
        return new LoggingResponseDecorator(generator);
    }
}